package java_thinking.unit_21._21_2;

import net.jcip.annotations.NotThreadSafe;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.math.BigInteger;

/**
 * @Desc:   2-2 一个没有同步情况下的案例，不要这么做
 *      1. ++count 并非原子操作，实际上包含了三个独立的操作：读取count值，将值+1，然后将计算结果写入count
 *        其结果状态依赖于之前的状态
 *      2.有可能在读取count值前后，其他线程进来读取count，两个线程读取到的都是9，结果两个线程
 *        执行结果都是count = 10，就丢失了一次操作计数
 *      3.这种依赖于观察结果来做出判断或者执行某个计算-先检查后执行使得结果变得不可靠
 * @author: cww
 * @DateTime: 2019/5/29 19:41
 */
@NotThreadSafe
public class UnsafeCountingFactory extends GenericServlet implements Servlet {
    private long count = 0;

    public long getCount() {
        return count;
    }
    @Override
    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = factor(i);
        ++count;
        encodeIntoResponse(resp, factors);
    }
    void encodeIntoResponse(ServletResponse res, BigInteger[] factors) {
    }

    BigInteger extractFromRequest(ServletRequest req) {
        return new BigInteger("7");
    }

    BigInteger[] factor(BigInteger i) {
        // Doesn't really factor
        return new BigInteger[] { i };
    }
}
